<template>
  <div class="map-container">
    <div id="map-container" ref="mapContainer"></div>

    <div class="style-switcher">
      <div
          v-for="style in mapStyles"
          :key="style.value"
          class="style-option"
          :class="{ active: currentStyle === style.value }"
          @click="changeMapStyle(style.value)"
      >
        <div class="style-preview" :style="{ backgroundColor: style.color }"></div>
        <span>{{ style.label }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 地图实例
const map = ref(null)
const mapContainer = ref(null)
const district = ref(null)
const polygon = ref(null)

// 当前样式
const currentStyle = ref('normal')

// 可用地图样式配置
const mapStyles = [
  { value: 'normal', label: '标准', color: '#ffffff' },
  { value: 'dark', label: '深色', color: '#1a1a1a' },
  { value: 'fresh', label: '清新', color: '#e6f3ff' },
  { value: 'light', label: '浅色', color: '#f5f5f5' },
  { value: 'grey', label: '灰色', color: '#cccccc' },
  { value: 'macaron', label: '马卡龙', color: '#f0e6ff' },
  { value: 'blue', label: '蓝色', color: '#e6f7ff' },
  { value: 'darkblue', label: '深蓝', color: '#001529' },
]

// 绘制行政区边界
const drawBounds = (districtName, level = 'province') => {
  console.log('1. 开始绘制边界')
  if (!map.value || !AMap) {
    console.error('地图未初始化或AMap未定义')
    return
  }
  console.log('2. AMap可用')

  try {
    // 每次创建新的DistrictSearch实例
    district.value = new AMap.DistrictSearch({
      subdistrict: 0,      // 不返回下级行政区
      extensions: 'all',   // 返回边界坐标
      level: level         // 设置查询级别
    })
    console.log('3. DistrictSearch实例创建成功')

    district.value.search(districtName, (status, result) => {
      console.log('4. 搜索回调执行', status)
      if (polygon.value) {
        map.value.remove(polygon.value)
        polygon.value = null
      }

      console.log('搜索结果:', result)

      if (status === 'complete' && result.info === 'OK') {
        // 注意：正确的属性名是 boundaries 不是 boundaries
        const bounds = result.districtList[0].boundaries
        console.log('获取到的边界数据:', bounds)

        if (bounds && bounds.length > 0) {
          polygon.value = new AMap.Polygon({
            strokeWeight: 1,
            path: bounds,
            fillOpacity: 0.2,
            fillColor: '#80d8ff',
            strokeColor: '#0091ea'
          })
          map.value.add(polygon.value)
          map.value.setFitView(polygon.value)
          console.log('5. 行政区划绘制完成')
        }
      } else {
        console.error('行政区查询失败 - 状态:', status, '结果:', result)
      }
    })
  } catch (error) {
    console.error('行政区查询出错:', error)
  }
}

// 全局保存AMap引用
let AMap = null

// 初始化地图
onMounted(() => {
  AMapLoader.load({
    key: '0f41dbd873f06ebbc5d14a8df71e3ff7',
    version: '2.0',
    plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.DistrictSearch']
  }).then((loadedAMap) => {
    AMap = loadedAMap // 保存AMap引用
    console.log('AMap加载成功:', AMap)

    map.value = new AMap.Map(mapContainer.value, {
      viewMode: '2D',
      zoom: 7,
      center: [104.065735, 30.659462],
      mapStyle: `amap://styles/${currentStyle.value}`
    })

    // 添加控件
    map.value.addControl(new AMap.ToolBar())
    map.value.addControl(new AMap.Scale())

    console.log('地图初始化完成，开始加载四川省')
    // 加载四川省行政区域
    drawBounds('四川省')

    // 添加成都标记点
    new AMap.Marker({
      position: [104.065735, 30.659462],
      title: '成都市',
      map: map.value
    })
  }).catch(e => {
    console.error('地图加载失败:', e)
  })
})

// 切换地图样式
const changeMapStyle = (style) => {
  if (!map.value) return
  currentStyle.value = style
  map.value.setMapStyle(`amap://styles/${style}`)
}
</script>

<style scoped>
/* 保持原有样式不变 */
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

#map-container {
  width: 100%;
  height: 100%;
}

.style-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 999;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-width: 300px;
}

.style-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s;
}

.style-option:hover {
  background: #f0f0f0;
}

.style-option.active {
  background: #e6f7ff;
  border: 1px solid #1890ff;
}

.style-preview {
  width: 40px;
  height: 20px;
  border-radius: 2px;
  margin-bottom: 4px;
  border: 1px solid #ddd;
}

.style-option.active .style-preview {
  border-color: #1890ff;
}
</style>